#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/12/21 14:56
# @Author  : Beam
# @Site    : 
# @File    : UserAuthentication.py
# @Software: PyCharm
'''中间件，用于认证页面是否已登录'''

from django.shortcuts import redirect
from config import setting


class MiddlewareMixin(object):
	#Django内置自带的类
    def __init__(self, get_response=None):
        self.get_response = get_response
        super(MiddlewareMixin, self).__init__()

    def __call__(self, request):
        response = None
        if hasattr(self, 'process_request'):
            response = self.process_request(request)
        if not response:
            response = self.get_response(request)
        if hasattr(self, 'process_response'):
            response = self.process_response(request, response)
        return response


class UserAuthent(MiddlewareMixin):
	def process_request(self, request):

		'''记得要排除login的页面，不然死循环了！！！'''

		import re

		urlpath = request.path_info

		for url in setting.URLS:
			if re.match(url,urlpath):
				return None
		userid = request.session.get('userid',None)
		if userid:
			return None
		else:
			return redirect('/login')
